﻿# -*- encoding: utf-8 -*- 
from itertools import groupby
from datetime import datetime, timedelta

from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools.misc import formatLang
import odoo.addons.decimal_precision as dp

from docx.enum.style import WD_STYLE_TYPE
from docx import Document
from docx.shared import Cm,Pt,RGBColor
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT

'''import comtypes.client
import pythoncom
import os
import comtypes.gen.Word
import comtypes.gen.PowerPoint'''
import pythoncom
from win32com.client import gencache
from win32com.client import constants, gencache



from datetime import datetime
import time

from odoo import http
from odoo.http import content_disposition, dispatch_rpc, request, \
    serialize_exception as _serialize_exception, Response

class cfarmc_contract_fhcontract(models.Model):
    _name = "cfarmc_contract.fhcontract"
    _inherit = ['cfarmc_contract.fhcontract'] 
    fhproject=fields.Many2one('cfarmc_project.fhproject',u'项目',default=lambda self: self._context.get('fproject_id_v1'),readonly=False,required=False,translate=False)
cfarmc_contract_fhcontract()


class cfarmc_project_fhproject(models.Model):
    _name = 'cfarmc_project.fhproject'
    _description = u'项目立项'
    _rec_name='fhproject_name'
    _inherit = ['portal.mixin','mail.thread','mail.activity.mixin']
    _order = 'id desc'    
    def get_employee(self):
        obj = self.env['hr.employee']
        idsobj = obj.search([('user_id','=',self.env.user.id)])
        print('-------------------------------------')		
        print(self.env.user.id)		
        #print(ids)	
        res = idsobj.read()
        print(res)					
        return res and res[0]['id'] or 0

        
    def get_organ(self):
        obj = self.env['res.users']
        idsobj = obj.search([('id','=',self.env.user.id)])
        res = idsobj.read()
        print(res)					
        return res and res[0]['fhorgan'] or 0
    def get_FConsultant(self,role): 
        obj = self.env['mybase.fh_role']      
        idsobj = obj.search([('fhname','=',role)],limit=1) 
        res = idsobj.read()				
        return res and res[0]['id'] or 0  
    def get_default_order_linefile(self):
        default_order_linefile= []  
        obj = self.env['cfarmc_project.default_order_linefile'].search([])  
        for item in obj:
            default_order_linefile.append([0, False, {'fhpro_stage':item.fhpro_stage,'fhtitle': item.title, 'fhcode': '1','fhv': 'A1','fstatus': '0','fhurl':'http://127.0.0.1:8069/u.doc', 'fdisable': '0',  'url': False, 'ext': 'doc', 'file': False, 'remarks': False, }])	  				
        return default_order_linefile
        
    def GET_FH_no(self):
        obj = self.env['res.users']
        idsobj = obj.search([('id','=',self.env.user.id)])					
        fhorgan_no=""
        fhorgan_id=0
        fh_no=""
        fh_oj_no=""
        for item in idsobj:
            fhorgan_no=item.fhorgan.fh_no
            fhorgan_id=item.fhorgan.id
        fhidsobj = self.search([('fhorgan','=',fhorgan_id)],limit=1,order='id desc')
        for item in fhidsobj:
            fh_no=str(item.fh_no+1)
        if(1==1):
            k=len(fh_no)
            if(k==0):
                fh_oj_no="0001"
            if(k==1):
                fh_oj_no="000"+fh_no 
            if(k==2):
                fh_oj_no="00"+fh_no  
            if(k==3):
                fh_oj_no="0"+fh_no
            if(k==4):
                fh_oj_no=""+fh_no 
        return [fh_oj_no,fhorgan_no+fh_oj_no]        
        
        
    order_linefile = fields.One2many('cfarmc_project.tbdesigninputlinefile', 'pay_id', string=u'相关文件', copy=True,default=lambda self: self.get_default_order_linefile()) 

    name = fields.Char(string='项目编号', required=True, copy=False, readonly=True,index=True, default=lambda self:_('/'))  
    fh_no = fields.Integer(string='项目编号', required=True, copy=False, readonly=True,index=True,default=0) 
    
    fhcompany=fields.Char(u'单位',readonly=False,required=False,translate=False)    
    fhproject_name=fields.Char(u'工程名称',readonly=False,required=False,translate=False)    
    fhproject_father=fields.Many2one('cfarmc_project.fhproject',u'父项目',)
    fhproject_type_lx=fields.Many2one('cfarmc_project.fhproject_type_lx',u'项目类型',)      
    fhproject_type=fields.Many2one('cfarmc_project.fhproject_type',u'项目类别',)  
    fhproject_phase=fields.Many2one('cfarmc_project.fhproject_phase',u'项目阶段',)    
    fhsource_funds=fields.Selection([('0',u'上级补助'),('1',u'村级自筹')],u'资金来源',readonly=False,required=False,translate=False)
    fhaddress=fields.Char(u'项目详细地址',readonly=False,required=False,translate=False)
    fhattribute=fields.Selection([('0',u'翻建'),('1',u'新建')],u'项目属性',readonly=False,required=False,translate=False)
    fhbudget=fields.Float(u'项目预算',readonly=False,required=False,translate=False)
    fhanalysis=fields.Text(u'可行性分析',readonly=False,required=False,translate=False)
    
    #state=fields.Selection([('draft',u'草稿'),('application',u'提报'),('approval1',u'村两委审核'),('approval2',u'村民代表审核'),('approval3',u'挂村领导审核'),('reject',u'驳回'),('approval4',u'审核通过')], u'状态', required=False, default='draft')    
    FAddperson =fields.Many2one('hr.employee',u'员工',readonly=False,required=False,translate=False,default=lambda self: self.get_employee())
    FAdddate1= fields.Datetime(u'提交时间',readonly=False,required=False,translate=False,default=fields.Datetime.now)
	
    #FConsultant1=fields.Many2one('hr.employee',u'村两委审核人',default=lambda self: self.get_FConsultant("村两委","1"),readonly=False,required=False,translate=False)	
    #FConsultant2=fields.Many2one('hr.employee',u'村民代表审核人',default=lambda self: self.get_FConsultant("村民代表","1"),readonly=False,required=False,translate=False)	
    #FConsultant3=fields.Many2one('hr.employee',u'挂村领导审核人',default=lambda self: self.get_FConsultant("挂村领导","0"),readonly=False,required=False,translate=False)	
    #FConsultant4=fields.Many2one('hr.employee',u'镇记账中心审核人',default=lambda self: self.get_FConsultant("镇记账中心","0"),readonly=False,required=False,translate=False)
	
    #fhgroups1=fields.Many2one('mybase.fh_role',u'村两委审核人',default=lambda self: self.get_FConsultant("村两委"),readonly=False,required=False,translate=False)
    #fhgroups2=fields.Many2one('mybase.fh_role',u'村民代表审核人',default=lambda self: self.get_FConsultant("村民代表"),readonly=False,required=False,translate=False)
    #fhgroups3=fields.Many2one('mybase.fh_role',u'挂村领导审核人',default=lambda self: self.get_FConsultant("挂村领导"),readonly=False,required=False,translate=False)
    #fhgroups4=fields.Many2one('mybase.fh_role',u'镇记账中心审核人',default=lambda self: self.get_FConsultant("镇记账中心"),readonly=False,required=False,translate=False)

    state=fields.Selection([('draft',u'新建'),('application',u'提报'),('approval1',u'预审通过'),('reject',u'驳回'),('approval4',u'终审通过')], u'状态', required=False, default='draft') 
    fhgroups1=fields.Many2one('mybase.fh_role',u'预审',default=lambda self: self.get_FConsultant("预审"),readonly=False,required=False,translate=False)
    fhgroups2=fields.Many2one('mybase.fh_role',u'终审',default=lambda self: self.get_FConsultant("终审"),readonly=False,required=False,translate=False)
    
    
    fhstate=fields.Selection([('draft',u'在建'),('application',u'结束')],u'项目状态')
    
    FAdddate2= fields.Datetime(u'审批时间',readonly=False,required=False,translate=False,default=fields.Datetime.now)
    order_line = fields.One2many('cfarmc_project.acceptline', 'pay_id', string='', copy=True)
    fhorgan=fields.Many2one('mybase.fhorgan',u'项目业主',default=lambda self: self.get_organ(),readonly=False,required=False,translate=False)  
    order_line2 = fields.One2many('cfarmc_project.fhprojectline2', 'pay_id', string='', copy=True)
    fhcontract=fields.Many2one('cfarmc_contract.fhcontract',u'合同',default=lambda self: self._context.get('fproject_id'),readonly=False,required=False,translate=False)
    
    @api.multi
    def attachment_image_preview(self):
        """附件上传 第二种方式"""
        self.ensure_one()
        model_data =self.env['ir.model.data'].sudo()      
        view_document_file_kanban = model_data.get_object_reference('mail','view_document_file_kanban')        
        view_attachment_tree = model_data.get_object_reference('base','view_attachment_tree')
        view_attachment_form = model_data.get_object_reference('base','view_attachment_form')    
        domain = [('res_model', '=', self._name), ('res_id', '=', self.id)]
        return {
        'domain': domain,
        'res_model': 'ir.attachment',
        'name': u'附件管理',
        'type': 'ir.actions.act_window',
        'view_id': False,
        'view_mode': 'kanban,tree,form',
        'view_type': 'form',
        'views': [ 
        (view_document_file_kanban and view_document_file_kanban[1] or False, 'kanban'),
        (view_attachment_tree and view_attachment_tree[1] or False, 'tree'),
        (view_attachment_form and view_attachment_form[1] or False, 'form')     
        ],         
        'limit': 20,
        'context': "{'default_res_model': '%s','default_res_id': %d}" % (self._name, self.id)
        }    
    @api.multi
    def attachment_image_preview_readonly(self):
        """附件上传 第二种方式"""
        self.ensure_one()
        model_data =self.env['ir.model.data'].sudo()      
        view_document_file_kanban = model_data.get_object_reference('myattachment','view_document_file_kanban')        
        view_attachment_tree = model_data.get_object_reference('myattachment','view_attachment_tree')
        view_attachment_form = model_data.get_object_reference('myattachment','view_attachment_form')       
        domain = [('res_model', '=', self._name), ('res_id', '=', self.id)]
        return {
        'domain': domain,
        'res_model': 'ir.attachment',
        'name': u'附件管理',
        'type': 'ir.actions.act_window',
        'view_id': False,
        'view_mode': 'kanban,tree,form',
        'view_type': 'form',
        'views': [ 
        (view_document_file_kanban and view_document_file_kanban[1] or False, 'kanban'),
        (view_attachment_tree and view_attachment_tree[1] or False, 'tree'),
        (view_attachment_form and view_attachment_form[1] or False, 'form')     
        ],         
        'limit': 20,
        'context': "{'default_res_model': '%s','default_res_id': %d}" % (self._name, self.id)
        }       
    @api.multi
    def action_cfarmc_project_print1(self):
        path =self.env['ir.config_parameter'].sudo().get_param('document_path_create_project')+"1.docx"
        document = Document(path)
        document.paragraphs[1].text="填表时间"+str(datetime.now().strftime("%Y-%m-%d")) 
        for table in document.tables:
        
            table.rows[0].cells[3].text=self.fhorgan.fhname 
            self.set_alignment(table.rows[0].cells[3])
            table.rows[0].cells[5].text=str(self.create_date.strftime("%Y-%m-%d"))
            self.set_alignment(table.rows[0].cells[5])            
        
            table.rows[1].cells[3].text=self.fhproject_name 
            self.set_alignment(table.rows[1].cells[3])
            if(self.fhsource_funds=="0"):
                table.rows[1].cells[5].text="1.上级补助(√)\n2.村级自筹(×)"
            else:                
                table.rows[1].cells[5].text="1.上级补助(×)\n2.村级自筹(√)" 
            print('self.fhaddress',self.fhaddress)
            if(self.fhaddress!="" and self.fhaddress!=False):
                table.rows[2].cells[3].text=self.fhaddress 
                self.set_alignment(table.rows[2].cells[3]) 
            
            if(self.fhattribute=="0"):
                table.rows[2].cells[5].text="1.翻建(√)\n2.新建(×)" 
            else:                
                table.rows[2].cells[5].text="1.翻建(×)\n2.新建(√)" 

            if(self.fhbudget!=0 and self.fhbudget!=False):                
                table.rows[3].cells[3].text=str(self.fhbudget)+ table.rows[3].cells[3].text 
                self.set_alignment(table.rows[3].cells[3]) 
            if(self.fhanalysis!="" and self.fhanalysis!=False):            
                table.rows[4].cells[3].text=self.fhanalysis
                self.set_alignment_text(table.rows[4].cells[3])              
        filepath1 = datetime.now().strftime("%Y%m%d%H%M%S%f")+".docx"	              
        document.save(self.env['ir.config_parameter'].sudo().get_param('document_path_create_project')+"村级工程建设项目立项备案表"+filepath1)
        return {
                'name':"download",
                'url':self.env['ir.config_parameter'].sudo().get_param('document_path_create_project_url')+"村级工程建设项目立项备案表"+filepath1,
                'type': 'ir.actions.act_url',
                'target': 'self'
            }
  
    '''def convertDocxToPDF(self,infile,outfile):
        pythoncom.CoInitialize()    
        wdFormatPDF = 17
        word = comtypes.client.CreateObject('Word.Application')
        doc = word.Documents.Open(infile)
        doc.SaveAs(outfile, FileFormat=wdFormatPDF)
        doc.Close()
        word.Quit()'''
    def convertDocxToPDF(self,wordPath, pdfPath):
        pythoncom.CoInitialize()
        word = gencache.EnsureDispatch("Word.Application")
        doc = word.Documents.Open(wordPath, ReadOnly=1)
        doc.ExportAsFixedFormat(pdfPath,
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
        word.Quit(constants.wdDoNotSaveChanges)
  
    @api.multi
    def action_cfarmc_project_print_pdf(self):
        infile=self.env['ir.config_parameter'].sudo().get_param('document_path_create_project')+"1.docx"  
        outfile=self.env['ir.config_parameter'].sudo().get_param('document_path_create_project')+"weishuai.pdf"
        print('---------------infile---------------',infile)
        print('------------outfile------------------',outfile)          
        self.convertDocxToPDF(infile,outfile)
        fhurl=self.env['ir.config_parameter'].sudo().get_param('document_path_create_project_url')+"weishuai.pdf"     
        print('-------fhurl---------',fhurl)         
        return {
                'name':"WORD预览",
                'url':"/cfarmc_project/static/fhword/index.html?fhurl="+fhurl,
                'type': 'ir.actions.act_url',
                'target': 'new'                      
               }
        
    def init_powerpoint(self):
       powerpoint = gencache.EnsureDispatch("Powerpoint.Application")
       powerpoint.Visible = 1
       return powerpoint        
        
    def ppt_to_pdf(self,powerpoint, inputFileName, outputFileName, formatType = 32):
       deck = powerpoint.Presentations.Open(inputFileName,ReadOnly=1)
       deck.ExportAsFixedFormat(outputFileName,2, PrintRange=None)
       deck.Close()
       time.sleep(3)

    @api.multi
    def action_cfarmc_project_print_ppt(self):
        pythoncom.CoInitialize()     
        powerpoint = self.init_powerpoint()
        inputFileName=self.env['ir.config_parameter'].sudo().get_param('document_path_create_project')+"ppt1.pptx" 
        outputFileName=self.env['ir.config_parameter'].sudo().get_param('document_path_create_project')+"pptpdf1.pdf" 
        self.ppt_to_pdf(powerpoint,inputFileName, outputFileName )
        powerpoint.Quit()
        fhurl=self.env['ir.config_parameter'].sudo().get_param('document_path_create_project_url')+"pptpdf1.pdf"     
        print('-------fhurl---------',fhurl)         
        return {
                'name':"WORD预览",
                'url':"/cfarmc_project/static/fhppt/index.html?fhurl="+fhurl,
                'type': 'ir.actions.act_url',
                'target': 'new'                      
               }
   
    def action_cfarmc_project_print_excle(self):    
        return {
                'name':"表格预览",
                'url':"/cfarmc_project/static/fhexcel/basic.html",
                'type': 'ir.actions.act_url',
                'target': 'new'                      
               }
                  
   
   
    def set_alignment(self,cell):         
        cell.paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.LEFT 
        cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER                
        return True  
    def set_alignment_text(self,cell):         
        cell.paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.LEFT 
        #cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER                
        return True  
    
    def action_property_file_report(self):    
        request.session.res_model=self._name
        request.session.res_id=self.id  
        #base_url="/web#id=37&action=316&model=cfarmc_project.fhproject&view_type=form&menu_id=216"        
        #request.session.url=base_url 
        #print('self._context',self)        
        #print('----self.driver.current_url:---------',base_url)
        return {
                'name':"附件上传",
                'url':"/myattachment/static/index.html",
                'type': 'ir.actions.act_url',
                'target': 'self'                      
               }
               
          
    @api.multi
    def action_cfarmc_project_print2(self):
    
        return True    
    @api.multi
    def action_cfarmc_project_fhtender(self):
    
        domaincontext=[('fhname','=',self.id)]    
    
        value = {
            'name': '查询向导',			
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'cfarmc_project.fhtender',
            'res_id': 1,
            'views': [(False, 'tree'),(False, 'form')],
            'type': 'ir.actions.act_window',
            'domain':domaincontext ,	
            'context':{'fproject_id':self.id},            
        }		
		
        return value
        
    @api.multi
    def action_cfarmc_contract_fhcontract(self):
    
        domaincontext=[('fhproject','=',self.id)]    
    
        value = {
            'name': '查询向导',			
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'cfarmc_contract.fhcontract',
            'res_id': 1,
            'views': [(False, 'tree'),(False, 'form')],
            'type': 'ir.actions.act_window',
            'domain':domaincontext ,
            'context':{'fproject_id_v1':self.id},                 
        }		
		
        return value 


    @api.multi
    def action_cfarmc_project_fhaccept(self):
    
        domaincontext=[('fhname','=',self.id)]    
    
        value = {
            'name': '查询向导',			
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'cfarmc_project.fhaccept',
            'res_id': 1,
            'views': [(False, 'tree'),(False, 'form')],
            'type': 'ir.actions.act_window',
            'domain':domaincontext ,
            'context':{'fproject_id':self.id},                 
        }		
		
        return value 
    @api.multi
    def action_cfarmc_project_file(self):
    
        domaincontext=[('fhproject','=',self.id)]    
    
        value = {
            'name': '查询向导',			
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'cfarmc_contract.file',
            'res_id': 1,
            'views': [(False, 'tree'),(False, 'form')],
            'type': 'ir.actions.act_window',
            'domain':domaincontext ,
            'context':{'fproject_id2':self.id},                 
        }		
		
        return value 
        
    def action_funproved0(self):
        t=fields.datetime.now()        
            
        self.sudo().write({'state':'application','FAdddate1':t})       
        return True

    def action_funproved1(self):
        t=fields.datetime.now()
        self.sudo().write({'state':'approval1','FAdddate2':t})                      
        return True	
	
    def action_funproved2(self):
        t=fields.datetime.now()
        self.sudo().write({'state':'approval2','FAdddate2':t})       
        return True					   

    def action_funproved3(self):
        t=fields.datetime.now()
        self.sudo().write({'state':'approval3','FAdddate2':t})       
        return True	
        
    def action_funproved4(self):
        t=fields.datetime.now()
        self.sudo().write({'state':'approval4','FAdddate2':t})       
        return True	

    def action_funproved5(self):
        t=fields.datetime.now()
        #self.write({'state':'reject','FAdddate2':t})
        self.sudo().write({'state':'draft','FAdddate2':t})  
        for item in self.order_line:
            item.write({'fhok':'1'})          
        return True	
    #编号方法
	
        
    @api.model		
    def create(self, vals):
                
        vals['fh_no']=int(self.GET_FH_no()[0])
        vals['name'] =self.GET_FH_no()[1]
        result = super(cfarmc_project_fhproject, self).create(vals)
        self.env['mybase.logging'].my_create_or_update('项目立项','新增',str(self.id),'新增机构记录')         
        return result
    @api.multi		
    def write(self, values):

        result = super(cfarmc_project_fhproject, self).write(values)	
        self.env['mybase.logging'].my_create('项目立项','修改',str(self.id),'修改机构记录')        
        return result
    @api.multi
    def unlink(self):
        result=super(cfarmc_project_fhproject, self).unlink()
        self.env['mybase.logging'].my_create_or_update('项目立项','删除',str(self.ids),'删除机构记录')	
        return result
    @api.multi
    def copy(self, default=None):
        result=super(cfarmc_project_fhproject, self).copy(default)         
        self.env['mybase.logging'].my_create('项目立项','复制',str(self.id),'复制机构记录') 
        return result 
    @api.multi
    def search(self, args, offset=0, limit=None, order=None, context=None, count=False):
        domain =None		
        domain = [('state', '=', '0')]		
        return super(cfarmc_project_fhproject, self).search(args, offset=offset, limit=limit, order=order, count=count)

		
cfarmc_project_fhproject() #对象定义结束

class cfarmc_project_tbdesigninputlinefile(models.Model):
    _name = 'cfarmc_project.tbdesigninputlinefile'
    _description = u'相关文档'
    #_rec_name='FClass'
    @api.multi
    #@api.depends('fstatus')    
    def _compute_amount(self):
        #default_days=self.env['ir.config_parameter'].sudo().get_param('fhend_time_if')     
        for record in self:
            record.fh_readonly=False         
            if(record.fhpro_stage=="0" and record.pay_id.state not in ['draft']):
                record.fh_readonly=True
            if(record.fhpro_stage=="1" and record.pay_id.state in ['approval4']):
                record.fh_readonly=False                 
            

				
    pay_id=fields.Many2one('cfarmc_project.fhproject',u'相关文档',required=True, ondelete='cascade', index=True, copy=False)
    fhcode = fields.Char(u"文件编号", size=100)	
    fhv = fields.Char(u"版本", size=100)
    fhurl = fields.Char(u"下载模板", size=100)		
    file = fields.Binary(u"文件", required=False)
    fhtitle = fields.Char(u"文件名", size=100)    
    title = fields.Char(u"文件名", size=100)
    ext = fields.Char(u"文件类型", size=5)
    remarks = fields.Char(u"备注", size=200)
    create_date = fields.Datetime(u"完成时间", readonly=True)
    write_date = fields.Datetime(u"最后修改时间", readonly=True)
    url = fields.Char('文件路径',readonly=True)
    fremarks=fields.Text(u'备注',readonly=False,required=False,translate=False)
    fhpro_stage=fields.Selection([('0',u'预审'),('1',u'终审'),], u'阶段', required=False, default='0')	
    fstatus=fields.Selection([('0',u'未完成'),('1',u'已经完成')],u'是否完成',readonly=False,required=False,translate=False)
    fh_readonly=fields.Boolean(u'是否只读',compute='_compute_amount',readonly=False,required=False,translate=False,)  
    fdisable=fields.Selection([('0',u'定制件'),('1',u'借用件'),('2',u'标准件')],u'备注栏',readonly=False,required=False,translate=False)	
    @api.multi		
    def write(self, values):      
        values["fstatus"]='1'
        result = super(cfarmc_project_tbdesigninputlinefile, self).write(values)
        return result           
cfarmc_project_tbdesigninputlinefile() #对象定义结束

class cfarmc_project_acceptline(models.Model):
    _name = 'cfarmc_project.acceptline'
    _description = u'详细信息'
    #_rec_name='FClass'
    def get_employee(self, cr, uid, context={}):
        obj = self.pool.get('hr.employee')
        ids = obj.search(cr, uid, [('user_id','=',uid)])
        res = obj.read(cr, uid, ids, ['id','name'], context)
        return res and res[0]['id'] or 0

    pay_id=fields.Many2one('cfarmc_project.fhproject',u'fhtest_weishui001tb',required=True, ondelete='cascade', index=True, copy=False)
    fmobile1= fields.Char(u'标题',readonly=False,required=False,translate=False)
    fremarks=fields.Text(u'备注',readonly=False,required=False,translate=False)
    FAddperson =fields.Many2one('hr.employee',u'经办人',readonly=False,required=False,translate=False)
    FAdddate= fields.Datetime(u'添加日期',readonly=False,required=False,translate=False)    
    FConsultant=fields.Many2one('hr.employee',u'班主任',readonly=False,required=False,translate=False)					   
    Fstatus=fields.Selection([('-1',u'提交'),('0',u'同意'),('1',u'驳回')],u'结果',readonly=False,required=False,translate=False)					   
    FDisable=fields.Selection([('0',u'启用'),('1',u'停用')],u'是否停用',readonly=False,required=False,translate=False)
    state=fields.Selection([('draft',u'草稿'),('application',u'提报'),('approval1',u'预审通过'),('reject',u'驳回'),('approval4',u'终审通过')], u'下个步骤', required=False, default='draft')     
    fhstate=fields.Selection([('0',u'正常'),('1',u'预警')],u'是否预警',default='0')
    fhok=fields.Selection([('0',u'正常'),('1',u'预警')],u'是否作废',default='0')     
    #定时执行程序
    @api.model
    def process_email_que(self,ids=None):
        print('------ok0--------',self) 


        for item in self.search([('fhok','=','0')]):
            if(item.state=="application"):
                print('------ok1--------')
                fh_workflow_project_application=self.env['ir.config_parameter'].sudo().get_param('fh_workflow_project_application')  
                m=(item.FAdddate + timedelta(minutes=int(fh_workflow_project_application))).strftime('%Y-%m-%d %H:%M:%S')
                T1=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                filters = [('state', '=','approval1'),('pay_id','=',item.pay_id.id),('FAdddate', '<=', m)]                 
                fhoj=self.search(filters)
                #print(item.FAdddate) 
                #print('M',m)  
                #print('T1',T1)    
                #print(filters)
                #print('fhoj.ids',fhoj.ids) 
                if(fhoj.ids!=[]):
                    if(T1<=m):
                        item.write({"fhstate":'0',})
                        print('------ok1_1111_20--------')                        
                    else:
                        item.write({"fhstate":'1',})                     
                        print('------ok1_1111_21--------')
                else:
                    if(T1<=m):
                        item.write({"fhstate":'0',})
                        print('------ok1_222_20--------')                        
                    else:
                        item.write({"fhstate":'1',})                     
                        print('------ok1_222_21--------')                                       
            if(item.state=="approval1"):
                print('------ok2--------')        
                fh_workflow_project_approval1=self.env['ir.config_parameter'].sudo().get_param('fh_workflow_project_approval1')  
                m=(item.FAdddate + timedelta(minutes=int(fh_workflow_project_approval1))).strftime('%Y-%m-%d %H:%M:%S')
                filters = [('state', '=','approval4'),('FAdddate', '<=', m),('pay_id','=',item.pay_id.id),('fhok','=','0')]                
                #fhoj=self.search(filters)
                T1=str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                filters = [('state', '=','approval1'),('pay_id','=',item.pay_id.id),('FAdddate', '<=', m)]                 
                fhoj=self.search(filters)
                #print(item.FAdddate) 
                #print('M',m)  
                #print('T1',T1)    
                #print(filters)
                #print('fhoj.ids',fhoj.ids) 
                if(fhoj.ids!=[]):
                    if(T1<=m):
                        item.write({"fhstate":'0',})
                        print('------ok1_1111_20--------')                        
                    else:
                        item.write({"fhstate":'1',})                     
                        print('------ok1_1111_21--------')
                else:
                    if(T1<=m):
                        item.write({"fhstate":'0',})
                        print('------ok1_222_20--------')                        
                    else:
                        item.write({"fhstate":'1',})                     
                        print('------ok1_222_21--------')                   

     
        return True
    
cfarmc_project_acceptline() #对象定义结束


class cfarmc_project_fhprojectline2(models.Model):
    _name = 'cfarmc_project.fhprojectline2'
    _description = u'详细信息'
    #_rec_name='FClass'
    def get_employee(self, cr, uid, context={}):
        obj = self.pool.get('hr.employee')
        ids = obj.search(cr, uid, [('user_id','=',uid)])
        res = obj.read(cr, uid, ids, ['id','name'], context)
        return res and res[0]['id'] or 0

    pay_id=fields.Many2one('cfarmc_project.fhproject',u'cfarmc_project_fhtender',required=True, ondelete='cascade', index=True, copy=False)

    file = fields.Binary(u"文件", required=True)
    title = fields.Char(u"文件名", size=100)
    ext = fields.Char(u"文件类型", size=5)
    remarks = fields.Char(u"备注", size=200)

    FAddperson =fields.Many2one('hr.employee',u'添加人',readonly=False,required=False,translate=False)
    FConsultant=fields.Many2one('hr.employee',u'班主任',readonly=False,required=False,translate=False)					   
    FAdddate= fields.Datetime(u'添加日期',readonly=False,required=False,translate=False)
    state=fields.Selection([('0',u'未分班'),('1',u'已分班')],u'是否分班',readonly=False,required=False,translate=False)					   
    FDisable=fields.Selection([('0',u'启用'),('1',u'停用')],u'是否停用',readonly=False,required=False,translate=False) 
cfarmc_project_fhprojectline2() #对象定义结束

